package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ComparatorProtos;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Override
    public void computeHotArticle() {
        Date date = DateTime.now().minusDays(200).toDate();
        List<ApArticle> articleListByLast5days = apArticleMapper.findArticleListByLast5days(date);
        List<HotArticleVo> hotArticleVoList =calculateScoreArticle(articleListByLast5days);

        //3.为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVoList);
    }

    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        ResponseResult channels = wemediaClient.getChannels();
        if (channels.getCode().equals(200)){
            String  channelJson = JSON.toJSONString(channels.getData());
            List<WmChannel> wmChannels = JSON.parseArray(channelJson, WmChannel.class);
            if (wmChannels.size()>0 && wmChannels!=null){
                for (WmChannel wmChannel : wmChannels) {
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(x -> x.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());
                    //给文章进行排序，取30条分值较高的文章存入redis  key：频道id   value：30条分值较高的文章
                    sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                }
            }
        }
        //设置推荐数据
        //给文章进行排序，取30条分值较高的文章存入redis  key：频道id   value：30条分值较高的文章
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        hotArticleVos= hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (hotArticleVos.size()>30){
            List<HotArticleVo> articleVos = hotArticleVos.subList(0, 30);
            cacheService.set(key,JSON.toJSONString(hotArticleVos));
        }
    }

    private List<HotArticleVo> calculateScoreArticle(List<ApArticle> articleListByLast5days) {
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        if (articleListByLast5days.size()>0 && articleListByLast5days!=null){
            for (ApArticle last5day : articleListByLast5days) {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(last5day,hot);
                Integer score=calculateScore(last5day);
                hot.setScore(score);
                hotArticleVoList.add(hot);
            }
        }
        return hotArticleVoList;
    }

    private Integer calculateScore(ApArticle last5day) {
        Integer score=0;
        if (last5day.getLikes()!=null){
            score+= last5day.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (last5day.getViews()!=null){
            score+=last5day.getViews();
        }
        if (last5day.getComment()!=null){
            score+=last5day.getComment()*ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(last5day.getCollection() != null){
            score += last5day.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
